package cn.flying.cloud.core.auth.session;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import cn.flying.cloud.base.common.enums.RtCodeEnum;
import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.Rt;
import cn.flying.cloud.core.auth.details.UserDetail;
import cn.flying.cloud.system.common.service.UserService;
import cn.flying.cloud.system.log.entity.SysLoginLog;

/**
 * @description: 正常session过期策略，或者服务重启导致session不可用
 * @author: admin
 * @date: 2023年06月02日 22:03
 * @version: 1.0
 */
@Component
public class SessionInvalidStrategy implements InvalidSessionStrategy {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserService userService;

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("当前登录已失效，请重新登录！");
        try {
            UserDetail userDetail = userService.findUserByUsername(request.getParameter("username"));
            if (Objects.nonNull(userDetail)) {
                //保存登录日志
                SysLoginLog log = new SysLoginLog();
                log.setUserId(userDetail.getUserId());
                log.setUserName(userDetail.getUsername());
                log.setName(userDetail.getName());
                log.setHappenType("会话失效");
                log.setHappenTime(LocalDateTime.now());
                log.setHappenIp(Ft.Network.getIpAddress(request));
                log.setRemark("会话过期失效");
                log.setTenantId(userDetail.getTenantId());
                log.setCreatedBy(userDetail.getUsername());
                log.setCreatedTime(LocalDateTime.now());
                log.setUpdatedBy(userDetail.getUsername());
                log.setUpdatedTime(LocalDateTime.now());
                log.setRevision(0L);
                userService.insertLoginLog(log);
            }
        } catch (Exception e) {
            logger.warn("系统登录日志保存失败，异常原因【{}】", e.getMessage());
        }

        //判断请求类型，根据不同的类型返回
        String xmlHttpRequest = "XMLHttpRequest";
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase(xmlHttpRequest)) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(Rt.error(RtCodeEnum.R10017)));
            out.flush();
            out.close();
        } else {
            //访问页面的直接跳转到登录页面
            new DefaultRedirectStrategy().sendRedirect(request, response, "/auth/login/page");
            //这里采用转发的方式，因为重定向后浏览器的地址变了
//            request.getRequestDispatcher("/auth/login/page").forward(request, response);
        }
    }
}
